#include "session_manager.hpp"
#include "../utils/logger.hpp"
#include <random>
#include <sstream>
#include <iomanip>

SessionManager& SessionManager::getInstance() {
    static SessionManager instance;
    return instance;
}

std::string SessionManager::generateToken() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 255);
    
    std::stringstream ss;
    for (int i = 0; i < 32; ++i) {
        ss << std::hex << std::setw(2) << std::setfill('0') << dis(gen);
    }
    return ss.str();
}

std::shared_ptr<Session> SessionManager::createSession(int userId, int expirySeconds) {
    std::string token = generateToken();
    std::string key = "session:" + token;
    
    if (RedisManager::getInstance().set(key, std::to_string(userId), expirySeconds)) {
        return std::make_shared<Session>(token, userId, expirySeconds);
    }
    return nullptr;
}

std::shared_ptr<Session> SessionManager::validateSession(const std::string& token) {
    std::string key = "session:" + token;
    std::string userIdStr = RedisManager::getInstance().get(key);
    
    if (userIdStr.empty()) {
        return nullptr;
    }
    
    try {
        int userId = std::stoi(userIdStr);
        // 获取剩余过期时间
        int ttl = RedisManager::getInstance().ttl(key);
        if (ttl <= 0) {
            return nullptr;
        }
        return std::make_shared<Session>(token, userId, ttl);
    } catch (const std::exception& e) {
        Logger::getInstance().error("Failed to parse user ID from session: {}", e.what());
        return nullptr;
    }
}

bool SessionManager::deleteSession(const std::string& token) {
    std::string key = "session:" + token;
    return RedisManager::getInstance().del(key);
} 